package com.liush.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liush.model.controller.SysRole;
import com.liush.model.controller.SysUserRole;
import com.liush.model.vo.AssginRoleVo;
import com.liush.model.vo.SysRoleQueryVo;
import com.liush.system.mapper.SysRoleMapper;
import com.liush.system.mapper.SysUserRoleMapper;
import com.liush.system.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author liush
 * @since 2023-02-25
 */
@Transactional
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public Page<SysRole> findPage(Page page, SysRoleQueryVo sysRoleQueryVo) {
        return sysRoleMapper.findPage(page, sysRoleQueryVo);
    }

    @Override
    public Map getRolesByUserId(Long userId) {
        Map map = new HashMap<>();
        // 查询所有的角色
        List<SysRole> allRoles = sysRoleMapper.selectList(null);
        map.put("allRoles", allRoles);
        // 给当前用户已经拥有的角色id赋值
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, userId);
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(queryWrapper);
        List<Long> userRoleIds = new ArrayList<>();
        sysUserRoles.forEach(sysUserRole -> {
            userRoleIds.add(sysUserRole.getRoleId());
        });
        map.put("userRoleIds", userRoleIds);
        return map;
    }

    @Override
    public void doAssignRole(AssginRoleVo assginRoleVo) {
        // 获取客户端已经分配的信息的角色id 和 用户id
        List<Long> roleIdList = assginRoleVo.getRoleIdList();
        Long userId = assginRoleVo.getUserId();
        // 删除当前用户分配的角色信息(用户和角色关系表的数据)
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, userId);
        sysUserRoleMapper.delete(queryWrapper);
        // 添加信息关系数据
        SysUserRole sysUserRole = new SysUserRole();
        roleIdList.forEach(roleId -> {
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(roleId);
            sysUserRoleMapper.insert(sysUserRole);
        });
    }
}
